package com.littlebee.storychild.common.utils;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class DBHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "servercenter"; // 数据库名
    private static final int version = 1; // 版本号

    private static DBHelper mInstance = null;
    private Context _context;

    private String versionTableName = "versionTable";  //版本
    private String dictTableName = "dict";         //数据字典
    private String keyWordsTableName = "keyWords";// 搜索关键字表
    private String rentTypeName = "renttype";// 土地用途

    private DBHelper(Context context) {
        super(context, DB_NAME, null, version);
        _context = context;
    }

    // 创建
    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            // 版本表
            String sql = "create table " + versionTableName
                    + " (name varchar(20))";
            db.execSQL(sql);

            // 区域表
            sql = "create table " + dictTableName + " (id integer primary key AUTOINCREMENT not null"
                    + ",code_name varchar(20) " + ",code_type varchar(20) "
                    + ",code_option varchar(20)" + ",code_value varchar(20) "
                    + ",sort varchar(20)"
                    + " ) ";
            db.execSQL(sql);

            // 搜索关键字表
            sql = "create table " + keyWordsTableName
                    + " (_id integer primary key autoincrement,name text)";
            db.execSQL(sql);

            // 土地用途
            //createRentTypeTable(db);

        } catch (Exception e) {
            //LogUtil.e(e.toString());
            e.printStackTrace();
        }

    }

    // 更新
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion == 1 && newVersion == 3) {
            //
        }

        if (newVersion == 3) {
            //

        }
        // 这里不能删除数据库，否则会报错
    }

    public void deleteDataBase() {
        _context.deleteDatabase(DB_NAME);
    }

    public static synchronized DBHelper getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new DBHelper(context);
        }

        return mInstance;
    }


    public String getVersion() {
        SQLiteDatabase db = getReadableDatabase();
        String version = "1.0";
        String sql = "select name from " + versionTableName;

        try {
            Cursor cursor = db.rawQuery(sql, null);

            if (cursor.moveToNext()) {
                version = cursor.getString(0);
            } else {
                ContentValues values = new ContentValues();
                values.put("name", version);
                db.insert(versionTableName, null, values);
            }

            cursor.close();
        } catch (Exception e) {
            //LogUtil.e(e.toString());
        }

        db.close();

        return version;
    }

    public void saveVersion(String version) {
        SQLiteDatabase db = getWritableDatabase();

        try {
            ContentValues values = new ContentValues();
            values.put("name", version);
            db.update(versionTableName, values, null, null);
        } catch (Exception e) {
            //LogUtil.e(e.toString());
        }

        db.close();
    }

    /**
     * 插入关键字
     *
     * @param keyword
     */
    public void insertKeyWord(String keyword) {
        SQLiteDatabase db = getWritableDatabase();
        insertCheck(db);
        try {
            ContentValues values = new ContentValues();
            values.put("name", keyword);
            db.insert(keyWordsTableName, null, values);
        } catch (Exception e) {
            //LogUtil.e(e.toString());
        }

        db.close();

    }

    /**
     * 查询所有关键字
     *
     * @return
     */
    public List<String> getHistoryKeyWords() {
        SQLiteDatabase db = getWritableDatabase();
        List<String> data = new ArrayList<String>();
        Cursor cur = null;
        try {
            String orderBy = "_id" + " DESC";
            cur = db.query(keyWordsTableName, null, null, null, null, null,
                    orderBy);
            cur.moveToFirst();
            for (int i = 0; i < cur.getCount(); i++) {
                String name = cur.getString(1);
                data.add(name);
                cur.moveToNext();
            }
        } catch (Exception e) {
            //LogUtil.e(e.toString());
        } finally {
            try {
                if (cur != null) {
                    cur.close();
                }
            } catch (Exception e) {
                //LogUtil.e(e.toString());
            }
        }
        db.close();
        return data;
    }

    /**
     * 插入搜索关键字前自检条数
     *
     * @return
     */
    private void insertCheck(SQLiteDatabase db) {
        Cursor cur = null;
        try {
            String orderBy = "_id" + " DESC";
            cur = db.query(keyWordsTableName, null, null, null, null, null,
                    orderBy);
            int count = cur.getCount();
            if (count == 30) {// 如果存满30条就删除最后一条
                cur.moveToLast();
                int id = cur.getInt(0);
                db.delete(keyWordsTableName, "_id=?", new String[]{id + ""});
            }

        } catch (Exception e) {
            //LogUtil.e(e.toString());
        } finally {
            try {
                if (cur != null) {
                    cur.close();
                }
            } catch (Exception e) {
                //LogUtil.e(e.toString());
            }
        }
    }

    /**
     * 清除搜索记录
     */

    public void clearHistoryKeyWords() {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(keyWordsTableName, null, null);
        db.close();
    }


}
